import os
import json

def getCargoContext(sentences, index):
    start_position = max(0, index - 2)
    end_position = -1 if index + 2 >= len(sentences) else index + 2 + 1
    return sentences[start_position:end_position]


def makepredictDataFromOneDailog(dialogue_sentences,cargo_name=""):
    result = []
    index = 0
    while index < len(dialogue_sentences):
        sentence = dialogue_sentences[index]
        if cargo_name not in sentence:
            index+=1
            continue
        cargo_context_list = getCargoContext(dialogue_sentences, index)
        result.append(cargo_context_list)
    return result



def getfiles(fold_name,return_fold=False):
    file_lists = []
    for root,dirs,files in os.walk(fold_name):
        for file in files:
            file_lists.append(os.path.join(root,file))
    return file_lists

import random
def generator_docanno_file(fold_path,save_path):
    output = []
    with open(save_path,'w',encoding='utf-8') as fwrite:

        generator_files = getfiles(fold_path)
        print(len(generator_files))
        for file in generator_files:
            with open(file,encoding='utf-8') as fread:
                try:
                    text = fread.read()
                    item = {}
                    item["text"] = text
                    output.append(item)
                except Exception as e:
                    print("error:"+file)

        random.shuffle(output)
        fwrite.write(json.dumps(output,indent=4,ensure_ascii=False))